package com.swyc.osschat.Test.IOTest.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @description 多路复用器
 * @Author: z156940l@outlook.com
 * @className SelectorTest
 * @Date: 2023/2/15 17:27
 */
public class SelectorTest {

    // 保存客户端连接
    static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        // 创建NIO ServerSocketChannel，与BIO的ServerSocket类似
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        // 设置ServerSocketChannel为非阻塞
        serverSocket.configureBlocking(false);
        // 打开selector处理channel，即创建epoll
        Selector selector = Selector.open();
        // 把ServerSocketChannel注册到selector上，并且selector对客户端accept连接操作感兴趣
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功");

        while (true){
            //阻塞等待处理的事件发生
            selector.select();

            // 获取selector中注册的全部事件的selectionKey 实例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            // 遍历selectionKeys对时间进行处理
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                // 如果是OP_ACCEPT事件，则进行连接获取时间注册
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel)key.channel();
                    SocketChannel socketChannel = server.accept();
                    socketChannel.configureBlocking(false);
                    // 这里只是注册了读时间，如果需要给客户端发送数据可以注册写数据
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("客户端连接成功。");
                }else if (key.isReadable()){
                    // 如果是OP_READ事件，则进行读取和打印
                    SocketChannel socketChannel = (SocketChannel)key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(6);
                    int len = socketChannel.read(byteBuffer);
                    // 如果有数据就把数据打印出来
                    if (len > 0){
                        System.out.println("接收到肖：" + new String(byteBuffer.array()));
                    }else if (len == -1){
                        //客户端断开，关闭socket
                        System.out.println("客户端断开连接.");
                        socketChannel.close();
                    }
                }
                // 防止重复处理
                iterator.remove();
            }
        }
    }
}
